const mongoose = require('mongoose');

const challengeSchema = new mongoose.Schema(
  {
    title: {
      type: String,
      required: [true, '挑战标题是必填项'],
      trim: true,
      maxlength: [100, '挑战标题不能超过100个字符'],
    },
    description: {
      type: String,
      required: [true, '挑战描述是必填项'],
      trim: true,
    },
    difficulty: {
      type: String,
      enum: ['初级', '中级', '高级'],
      default: '初级',
    },
    category: {
      type: String,
      enum: ['逻辑', '算法', '游戏', '动画', '音乐', '艺术', '故事', '综合'],
      required: true,
    },
    concepts: [String], // 涉及的编程概念，如循环、条件、变量等
    instructions: [{
      step: Number,
      content: String,
      hint: String,
    }],
    startingTemplate: {
      blocks: Object, // 初始积木配置
      sprites: [Object], // 初始角色配置
      stage: Object, // 初始舞台配置
    },
    expectedOutput: {
      type: Object, // 期望的输出或结果
      description: String, // 结果描述
    },
    testCases: [{
      input: Object,
      expectedOutput: Object,
      description: String,
    }],
    timeLimit: {
      type: Number, // 完成挑战的时间限制（分钟）
      default: 30,
    },
    points: {
      type: Number, // 完成挑战可获得的积分
      default: 10,
    },
    badges: [{
      name: String,
      description: String,
      imageUrl: String,
      conditions: Object, // 获得徽章的条件
    }],
    hints: [{
      content: String,
      unlockCost: Number, // 解锁提示需要的积分或虚拟货币
    }],
    relatedResources: [{
      title: String,
      type: String, // 视频、文章、项目等
      url: String,
    }],
    creator: {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'User',
    },
    isOfficial: {
      type: Boolean, // 是否为官方挑战
      default: false,
    },
    isPublic: {
      type: Boolean, // 是否公开
      default: true,
    },
    stats: {
      attempts: {
        type: Number,
        default: 0,
      },
      completions: {
        type: Number,
        default: 0,
      },
      averageCompletionTime: {
        type: Number, // 平均完成时间（分钟）
        default: 0,
      },
      rating: {
        type: Number, // 平均评分（1-5）
        default: 0,
      },
      ratingCount: {
        type: Number, // 评分人数
        default: 0,
      },
    },
    prerequisites: [{
      type: mongoose.Schema.Types.ObjectId,
      ref: 'Challenge',
    }],
    nextChallenges: [{
      type: mongoose.Schema.Types.ObjectId,
      ref: 'Challenge',
    }],
    ageRange: {
      min: {
        type: Number,
        default: 6,
      },
      max: {
        type: Number,
        default: 16,
      },
    },
  },
  {
    timestamps: true,
  }
);

// 创建索引以提高查询性能
challengeSchema.index({ difficulty: 1 });
challengeSchema.index({ category: 1 });
challengeSchema.index({ concepts: 1 });
challengeSchema.index({ isOfficial: 1, isPublic: 1 });
challengeSchema.index({ 'stats.rating': -1 });
challengeSchema.index({ 'ageRange.min': 1, 'ageRange.max': 1 });

const Challenge = mongoose.model('Challenge', challengeSchema);

module.exports = Challenge;